<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" size="small" inline>
      <el-form-item :label="$t('Department')" prop="deptId">
        <department-select v-model="queryParams.deptId" style="width: 200px" />
      </el-form-item>
      <el-form-item :label="$t('Name')" prop="name">
        <el-input v-model="queryParams.name" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t("Search") }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t("Reset") }}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['device:locker:create']">{{ $t("Add") }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="singleDisable" @click="handleDelete"
          v-hasPermi="['device:locker:delete']">{{ $t("Delete") }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain size="mini" @click="analysisVisible=true">{{ $t('analysis.Analysis') }}
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="queryPage"></right-toolbar>
    </el-row>

    <el-dialog :visible.sync="analysisVisible" fullscreen>
      <analysis-chart />
    </el-dialog>

    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="45" align="center" />
      <el-table-column label="#" type="index" width="45" align="right">
        <template slot-scope="scope">
          <span>{{
            (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1
          }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('Name')" align="left" prop="name" min-width="150">
        <template slot-scope="{ row }">
          <el-button type="text" @click="handleControll(row)">{{
            row.name
          }}</el-button>
        </template>
      </el-table-column>
      <el-table-column :label="$t('Code')" align="center" prop="code" min-width="150" />
      <el-table-column :label="$t('CreateTime')" align="left" prop="createTime" min-width="120" />
      <el-table-column :label="$t('Online')" align="center" prop="state" width="66">
        <template slot-scope="{ row }">
          <i v-if="row.online" class="el-icon-success success">{{
            $t("Yes")
          }}</i>
          <i v-else class="el-icon-error info">{{ $t("No") }}</i>
        </template>
      </el-table-column>
      <!-- <el-table-column :label="$t('common.OnOff')" align="center" prop="state" width="66">
        <template slot-scope="{ row }">
          <i v-if="row.state === 1" class="el-icon-success success">{{$t("On") }}</i>
          <i v-else class="el-icon-remove info">{{ $t("Off") }}</i>
        </template>
      </el-table-column> -->
      <!-- <el-table-column :label="$t('State')" align="center" prop="state" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.haij_device_state" :value="scope.row.state" />
        </template>
      </el-table-column> -->
      <el-table-column :label="$t('Operate')" align="center" width="120" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-hasPermi="['device:child:page']" v-if="paramtersByType(scope.row.type).hasChildren" size="mini"
            type="text" @click="handleChild(scope.row)" :title="$t('Child')">{{ $t('Child') }}</el-button>
          <el-button v-hasPermi="['device:locker:edit']" size="mini" type="text" icon="el-icon-edit"
            @click="handleUpdate(scope.row)" :title="$t('Modify')"></el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['device:locker:remove']" :title="$t('Delete')"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="queryPage" />

    <el-dialog :title="form.name" :visible.sync="showController" width="705px">
      <locker-controller v-model="form" />
    </el-dialog>

    <!-- 添加或修改设备对话框 -->
    <el-dialog :title="title" :visible.sync="formVisible" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-position="left" label-width="120px">
        <el-form-item v-if="form.id" :label="$t('Category')" prop="type">
          <dict-tag :options="dict.type.haij_device_type" :value="form.type" />
        </el-form-item>
        <el-form-item :label="$t('Code')" prop="code">
          <el-input v-model="form.code" :placeholder="$t('device.InsertCode')" />
        </el-form-item>
        <el-form-item :label="$t('Mode')" prop="mode">
          <dict-number-select v-model="form.mode" :dict="dict.type.haij_device_mode"
            :placeholder="$t('device.InsertMode')" />
        </el-form-item>
        <el-form-item :label="$t('Department')" prop="deptId">
          <department-select v-model="form.deptId" :placeholder="$t('device.InsertDepartment')" />
        </el-form-item>
        <el-form-item :label="$t('Name')" prop="name">
          <el-input v-model="form.name" :placeholder="$t('device.InsertName')" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="formSubmit">{{ $t("OK") }}</el-button>
        <el-button @click="formCancel">{{ $t("Cancel") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import lockerAPI from "@/api/device/device";
  import socketAPI from "@/api/socket/socket";
  import DataEntity from "@/components/DataEntity/DataEntity";
  import DepartmentSelect from "@/views/system/components/DepartmentSelect.vue";
  import LockerController from '@/views/device/components/controller/LockerController.vue';
  import AnalysisChart from '@/views/device/analysis/AnalysisChart.vue';
  import {
    paramtersByType,
    DeviceType
  } from '../common'

  const deviceOptions = [
    ['On', 'Open', 'Off']
  ]

  export default {
    name: "Device",
    dicts: ["haij_device_type", "haij_device_mode", "haij_device_state"],
    mixins: [DataEntity],
    components: {
      DepartmentSelect,
      LockerController,
      AnalysisChart
    },
    data() {
      return {
        currentAPI: lockerAPI,
        currentBaseURL: '/device/device',
        currentCode: 'device-locker',
        deviceOptions,
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          code: null,
          name: null,
          state: null,
          type: DeviceType.LOCKER
        },
        defaultForm: {
          id: null,
          name: null,
          code: null,
          mode: null,
          deptId: null
        },
        rules: {
          name: [{
            max: 20,
            message: this.$t("MaxLengthIs", [20]),
          }],
          code: [{
            required: true,
            message: this.$t("device.CodeNull"),
            trigger: "blur",
          }, {
            max: 50,
            message: this.$t("MaxLengthIs", [50]),
          }],
          deptId: [{
            required: true,
            message: this.$t("common.DepartmentNull"),
            trigger: "blur",
          }],
          mode: [{
            required: true,
            message: this.$t("device.SelectMode"),
            trigger: "blur",
          }, ],
        },
        showController: false,
        monthIdleVisible: false,
        analysisVisible: false,
        customVisible: false,
        customPieVisible: false
      };
    },
    watch: {
      list(nv, ov) {
        if (!ov || ov.length == 0) {
          this.subscribeDevices(nv);
          return
        }
        if (!nv || nv.length === 0) {
          this.subscribeDevices(nv);
          return
        }
        const om = {}
        const nm = {}
        ov.forEach(item => {
          if (item.code) {
            om[item.code] = item
          }
        })
        nv.forEach(item => {
          if (item.code) {
            nm[item.code] = item
          }
        })
        Object.keys(nm).forEach(k => {
          if (nm[k]) {
            delete om[k]
            delete nm[k]
          }
        })
        const removeList = []
        const addList = []
        Object.values(om).forEach(v => {
          removeList.push(v)
        })
        Object.values(nm).forEach(v => {
          addList.push(v)
        })
        this.unsubscribeDevices(removeList);
        this.subscribeDevices(addList);
      },
    },
    created() {
      this.subscribeDevices(this.list)
      socketAPI.addHandle(this.websocketReceive);
    },
    methods: {
      paramtersByType,
      handleAdd(formName) {
        this.form = {
          id: null,
          code: null,
          name: null,
          category: null,
          type: null,
          state: null,
          path: null,
          mojorNumber: null,
          deptId: null,
        };
        this.resetForm(formName);
        this.title = this.$t("Create");
        this.formVisible = true
      },
      subscribeDevices(list) {
        if (!list || list.length === 0) {
          return;
        }
        socketAPI.subscribe(list.map((item) => item.code));
      },
      unsubscribeDevices(list) {
        if (!list || list.length === 0) {
          return;
        }
        socketAPI.unsubscribe(list.map((item) => item.code));
      },
      handleChild(row) {
        this.$router.push({
          name: 'Device-child',
          query: {
            deviceId: row.id
          }
        })
      },
      handleControll(row) {
        this.showController = true;
        this.form = Object.assign({}, row);
      },
      websocketReceive(json) {
        if (!this.list || this.list.length == 0) {
          return
        }
        this.list.forEach((item) => {
          if (json.code !== item.code) {
            return;
          }
          const {
            state,
            status,
            online
          } = json;
          item.online = online;
          item.state = state;
          item.status = status;
        });
      }
    },
  };

</script>
